package chances.wechat.web.qr;

import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import chances.wechat.entity.QrCodeInfo;
import chances.wechat.log.WechatLogger;
import chances.wechat.service.QrCodeFactory;

@RestController
@RequestMapping(path = "/qr")
public class QrCodeController {

	@Value("${weixin.scan.url}")
	private String host;

	@Autowired
	private QrCodeFactory qrCodeFactory;

	@Autowired
	WechatLogger wxLogger;

	static Logger logger = LoggerFactory.getLogger("qr");
	
	
	@RequestMapping(value = "/scanUpdate")
	public void scanUpdate(@RequestParam String state, HttpServletResponse response) 
			throws IOException {
		qrCodeFactory.updateScanTime(state);
	}

	@RequestMapping(value = "/code/{iptvacct}/{stbtype}/{epgversion}")
	public void code(@PathVariable String iptvacct , @PathVariable String stbtype, @PathVariable String epgversion, HttpServletResponse response) throws IOException {
		logger.debug("user qr code, {},{},{}",iptvacct,stbtype,epgversion);
		
		
		response.setContentType("image/jpg");
		// 每次生成二维码保存相关信�?
		QrCodeInfo aQrCodeInfo = new QrCodeInfo(iptvacct, stbtype, epgversion);
		//String url = host + aQrCodeInfo.getQrInfo();
		//String url = String.format(host, aQrCodeInfo.getQrInfo());
		String url = host + aQrCodeInfo.getQrInfo() + ".wx";
		wxLogger.logQrCode(iptvacct, stbtype, epgversion, aQrCodeInfo.getQrInfo(), url);

		aQrCodeInfo = qrCodeFactory.pickQrCode(aQrCodeInfo);


		ServletOutputStream outputStream = response.getOutputStream();
		try {
			QRCodeUtil.encode(url, outputStream);
		} catch (Exception e) {
			e.printStackTrace();
		};
		outputStream.flush();
		outputStream.close();
	}

	@RequestMapping(value = "/qrCode")
	public String qrCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		response.setContentType("image/jpg");
	
		
		String iptvacct = request.getParameter("iptvacct");
		String stbtype = request.getParameter("stbtype");
		String epgversion = request.getParameter("epgversion");
		
		 code(iptvacct,stbtype,epgversion,response);
		return null;
	}
}
